// 登录注册
import { reqGetCode ,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout } from "@/api";
const state = {
  // 验证码
    code:'',
    token: localStorage.getItem('TOKEN'),
    userInfo:'',
   
   
};

const mutations = {
  // 验证码
    GETCODE(state,code){
        state.code = code;
    },
    USERLOGIN(state,token){
      state.token = token;
    },
    GETUSERINFO(state,userInfo){
      state.userInfo = userInfo;

    },
    // 清除本地数据
    CLEAR(state){
      state.token = '';
      state.user = {};
      localStorage.removeItem("TOKEN");
      state.userInfo = {};


    }



};

const actions = {
  // 获取验证码
 async getCode({commit},phone){
      let result =  await reqGetCode(phone); 
      if(result.code == 200){
        commit("GETCODE",result.data);
        return 'ok'

      }else{
        return Promise.reject(new Error('faile'))
      }
    },
    // 注册账号
   async userRegister({commit},user){
 let result =  await  reqUserRegister(user);
      if(result.code == 200){
        return 'ok';
      }else{
        return Promise.reject(new Error('faile'))
      }
    },

    // 登录业务tokenl令牌,vuex不能存储长时间存储数据，所以把token存在本地
  async userlogin({commit},data){
   let result =  await reqUserLogin(data);
  //  服务器下发token，用户唯一标识符(uuid)
  // 将来经常通过带token找服务器要用户信息进行展示
   console.log(result);
   if(result.code==200){
    // 用户已经登录成功且获取到了token
    commit("USERLOGIN",result.data.token);
    // 持久化存储token
    localStorage.setItem("TOKEN",result.data.token)
 
    return 'ok'
   } else{
    return Promise.reject(new Error('faile'))
   }
    },
    // 获取用户信息
  async  getUserInfo({commit}){
  let result  = await reqUserInfo();
  if (result.code == 200){
    commit("GETUSERINFO",result.data);
    

  }
    },
    // 退出登录
   async userLogout({commit}){
    // 只是向服务器发起一次请求通知服务器清除token
    // action里面不能操作state，要提交到mutations
   let result =  await reqLogout();
   if(result.code==200){
    commit("CLEAR",result.data)
    return 'ok';
   }else{
    return Promise.reject(new Error('faile'))
   }
    },




};

const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
